package com.stylefeng.guns.modular.system.controller;
import com.alibaba.fastjson.JSONObject;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.cache.CacheKit;
import com.stylefeng.guns.core.common.Tools.CodeMsg;
import com.stylefeng.guns.core.common.Tools.Result;
import com.stylefeng.guns.core.shiro.ShiroUser;
import com.stylefeng.guns.core.support.HttpKit;
import com.stylefeng.guns.core.util.HttpUtil;
import com.stylefeng.guns.modular.system.model.UserCw;
import com.stylefeng.guns.modular.system.service.IUserCwService;
import com.stylefeng.guns.util.CommonImportExcelServiceController;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * 公用文件上传
 * @author sasazaixian
 * @Date 2017年1月11日 下午1:08:17
 */
@Controller
@RequestMapping(value = {"/uploadFile"})
public class UploadFileController extends BaseController {
    @Value("${spring.fileServerUrl}")
    private String fileServerUrl;

    @Autowired
    private IUserCwService userCwService;
    /**
     * 公用文件上传
     *  @author sasazaixian@2018-10-24
     *  1.多文件上传必须在启动类上添加@EnableAutoConfiguration(exclude = {MultipartAutoConfiguration.class}) 否则MultipartFile[] files永远为空
     *  2.启用multipartResolver配置，详见UploadFileConfig，
     */
    @ApiOperation(value = "公用文件上传", notes = "公用文件上传", httpMethod = "POST")
    @CrossOrigin
    @PostMapping("/uploadFile")
    @ResponseBody  //uploadify 文件控件name:Filedata,所以注意。

    public Result uploadFile(@RequestParam("Filedata") MultipartFile[] files) {
        HttpServletRequest request=HttpKit.getRequest();
        String filetype = request.getParameter("filetype").toString();
        String processtype = request.getParameter("processtype").toString();
        String processid = request.getParameter("processid").toString();
        String iswater=request.getParameter("iswater").toString();
        String delid="";
        if(request.getParameter("delid")!=null){
            delid=request.getParameter("delid").toString();
        }
        String newfilename="";
        if(request.getParameter("newfilename")!=null){
            newfilename=request.getParameter("newfilename").toString();
            try {
                newfilename=java.net.URLDecoder.decode(newfilename, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        String fid="";
        ShiroUser sysUser=null;
        sysUser=getShiroUser();
        String loginId="";
        String orgId="";
        String loginName="";
        String orgName="";
        if(sysUser!=null ){
            loginId=""+sysUser.getId();
            orgId=""+sysUser.getSoId();
            loginName=sysUser.getName();
            orgName=sysUser.getSoName();
        }

        fid+=orgId+";";
        fid+=loginId+";";
        fid+=processid+";";
        fid+=processtype+";";
        fid+=filetype+";";
        fid+=loginName+";";
        fid+=orgName+";";
        fid+=newfilename+";";
        fid+=iswater+";";
        fid+=delid;
        try {
            fid=java.net.URLEncoder.encode(fid, "utf-8");
            if(files!=null && files.length>0){
                Map<String,String> pramsMap=new HashMap<String,String>();
                pramsMap.put("fid",fid);
                String result=HttpUtil.uploadFileByPost(files, fileServerUrl+"/uploadfileServlet", pramsMap);
                result=java.net.URLDecoder.decode(result,"utf-8");
                JSONObject jsonObj=JSONObject.parseObject(result);
                pramsMap.clear();
                pramsMap.put("message",jsonObj.getString("msg"));
                pramsMap.put("fileid",jsonObj.getString("fileid"));
                return Result.success(pramsMap);
            }else{
                return Result.error(CodeMsg.NOT_FIND_DATA, "未接受到文件！");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(CodeMsg.NOT_FIND_DATA, e.getMessage());
        }
    }
    /**
     * 公用文件Excel
     *  @author sasazaixian@2018-10-24
     */
    @ApiOperation(value = "公用上传excel", notes = "公用上传excel", httpMethod = "POST")
    @PostMapping("/uploadFileXls")
    @ResponseBody
    public Result uploadFileXls() {
        String message="";
        HttpServletRequest request=HttpKit.getRequest();
        try {
            String funName=request.getParameter("funName").toString();
            List<FileItem> fileItemList=null;
            DiskFileItemFactory fac = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(fac);
            upload.setSizeMax(20971520);
            fileItemList = upload.parseRequest(new ServletRequestContext(request));
            if(fileItemList!=null && fileItemList.size()>0){
                InputStream in=null;
                for (Iterator<FileItem> it = fileItemList.iterator(); it.hasNext();) {
                    FileItem item = it.next();
                    if (item.isFormField()) {
                        continue;
                    }
                    in=item.getInputStream();
                    break;
                }
                if(in==null){
                    return Result.error(CodeMsg.NOT_FIND_DATA, "后台未收到文件");
                }

                if(funName.equals("importuserInf")){//导入用户
                   List<UserCw> listUser =new ArrayList<UserCw>();
                   String  mess=CommonImportExcelServiceController.importUserInf(in, null, listUser);
                   if(mess.length()>0){
                       return Result.error(CodeMsg.NOT_FIND_DATA, mess);
                   }
                   //调用service保存数据入库

                }else if(funName.equals("importkhOrder")){//导入SIM信息


                }else{
                    return Result.error(CodeMsg.NOT_FIND_DATA, "未找到后代对应的解析方法!");
                }
            }else{
                return Result.error(CodeMsg.NOT_FIND_DATA, "后台未收到文件！");
            }
        }catch(InvocationTargetException ex){
            String mess=ex.getTargetException() == null? ex.getMessage():ex.getTargetException().getMessage();
            return Result.error(CodeMsg.NOT_FIND_DATA, mess);

        }catch (Exception ex) {
            return Result.error(CodeMsg.NOT_FIND_DATA, ex.getMessage());
        }
        return Result.success();
    }

    @Cacheable(value="local",key = "'userCw_'+#result.getId()")
    public  ShiroUser getShiroUser(){
        String token= getHttpServletRequest().getHeader("Authorization").substring(7);
        return CacheKit.get(CACHE_STRATEGY,token);
    }
}
